(function () {
  // socketio adapter
  const __socketioAdapter = {
    _io: null,
    initialize(io) {
      const self = this;
      self._io = io;
      $(document).on('echo-ready', function () {
        // reset
        self._io.reset();
      });
      // visibilitychange
      $(document).on('visibilitychange', function () {
        if (document.visibilityState === 'hidden') {
          self._io.disconnect();
        }
        if (document.visibilityState === 'visible') {
          if (!util.user.op.anonymous) {
            self._io.connect();
          }
        }
      });
      // reset
      self._io.reset();
    },
    socket() {
      // url
      const url = '<%=site.serverUrl%>';
      // opts
      const opts = {
        autoConnect: false,
        withCredentials: true,
        transports: ['websocket'],
      };
      opts.query = {
        'x-scene': util.user.provider.scene,
        'x-clientid': util.clientId,
      };
      return window.io(url, opts);
    },
    user() {
      return util.user;
    },
    logout() {
      location.reload(true);
    },
  };

  // socketio
  Object.defineProperty(util, 'io', {
    get() {
      if (!util.__io) {
        const SocketIO = window.socketio.default;
        util.__io = SocketIO.io(__socketioAdapter);
      }
      return util.__io;
    },
  });
})();
